package com.tanhua.dubbo.server.api;

import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.Method;
import cn.hutool.json.JSONException;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.dubbo.server.config.HuanXinConfig;
import com.tanhua.dubbo.server.enums.HuanXinMessageType;
import com.tanhua.dubbo.server.mapper.HuanXinUserMapper;
import com.tanhua.dubbo.server.pojo.HuanXinUser;
import com.tanhua.dubbo.server.service.RequestService;
import com.tanhua.dubbo.server.service.TokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.Arrays;
import java.util.Date;



@Service(version = "1.0.0")
@Slf4j
public class HuanXiApiImpl implements HuanXinApi {
    @Autowired
    private TokenService tokenService;
    @Autowired
    private HuanXinUserMapper huanXinUserMapper;
    @Autowired
    private HuanXinConfig huanXinConfig;
    @Autowired
    private RequestService requestService;
    @Override
    public String getToken() {
        String token = tokenService.getToken();
        return token;
    }

    @Override
    public Boolean register(Long userId) {
        String targetUrl=huanXinConfig.getUrl()+huanXinConfig.getOrgName()
                +"/"+huanXinConfig.getAppName()+"/users";
        HuanXinUser huanXinUser = new HuanXinUser();
        huanXinUser.setUsername("HX_"+userId);
        huanXinUser.setPassword(IdUtil.simpleUUID());
        HttpResponse response = requestService.execute(targetUrl, JSONUtil.toJsonStr(Arrays.asList(huanXinUser)), Method.POST);
        if(response.isOk()){
            huanXinUser.setUserId(userId);
            huanXinUser.setCreated(new Date());
            huanXinUser.setUpdated(huanXinUser.getCreated());
            huanXinUserMapper.insert(huanXinUser);
            return true;
        }
        return false;
    }

    @Override
    public HuanXinUser queryHuanXinUser(Long userId) {
        QueryWrapper<HuanXinUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        HuanXinUser huanXinUser = huanXinUserMapper.selectOne(queryWrapper);
        return huanXinUser;
    }

    @Override
    public HuanXinUser queryUserByUserName(String userName) {
        QueryWrapper<HuanXinUser> wrapper = new QueryWrapper<>();
        wrapper.eq("username", userName);
        return this.huanXinUserMapper.selectOne(wrapper);
    }

    @Override
    public Boolean addUserFriend(Long userId, Long friendId) {
        ///{org_name}/{app_name}/users/{owner_username}/contacts/users/{friend_username}
        String targetUrl=huanXinConfig.getUrl()+huanXinConfig.getOrgName() +"/"
                        +huanXinConfig.getAppName()+"/users/HX_"+userId+"/contacts/users/HX_"+friendId;
        try {
            // 404 -> 对方未在环信注册
            return this.requestService.execute(targetUrl, null, Method.POST).isOk();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 添加失败
        return false;
    }

    @Override
    public Boolean removeUserFriend(Long userId, Long friendId) {
        String targetUrl=huanXinConfig.getUrl()+huanXinConfig.getOrgName() +"/"
                +huanXinConfig.getAppName()+"/users/HX_"+userId+"/contacts/users/HX_"+friendId;
        try {
            return this.requestService.execute(targetUrl, null, Method.DELETE).isOk();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 删除失败
        return false;
    }

    @Override
    public Boolean sendMsgFromAdmin(String targetUserName, HuanXinMessageType huanXinMessageType, String msg) {
        try {
            String targetUrl=huanXinConfig.getUrl()+huanXinConfig.getOrgName()
                    +"/"+huanXinConfig.getAppName()+"/message";
            String body = JSONUtil.createObj().set("target_type", "users")
                    .set("target", JSONUtil.createArray().set(targetUserName))
                    .set("msg", JSONUtil.createObj().set("type", huanXinMessageType.getType())
                            .set("msg", msg)).toString();
            return requestService.execute(targetUrl,body,Method.POST).isOk();
        } catch (Exception e) {
            log.error("发送消息失败~ targetUserName = " + targetUserName+", type = " + huanXinMessageType.getType()+", msg = " + msg, e);
        }
        return false;
    }
}
